package com.ciwong.epaper.modules.share;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.Gravity;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * Created by young on 2017/3/27.
 * 微信分享类
 */
public class WxShareHelper {
    private static volatile WxShareHelper instance;
    private Context mContext;
    private WxShareListener mWxShareListener;
    private IWXAPI mShareIWXAPI;
    private BaseResp mbaseResp;
    private boolean isNeedDealWithResult = false;


    private WxShareHelper() {
    }

    public static WxShareHelper getInstance() {
        if (instance == null) {
            synchronized (WxShareHelper.class) {
                if (instance == null) {
                    instance = new WxShareHelper();
                }
            }
        }
        return instance;
    }

    public void initWxShare(Context context, WxShareListener mWxShareListener) {
        try {
            this.mContext = context;
            this.mWxShareListener = mWxShareListener;
            this.mShareIWXAPI = WXAPIFactory.createWXAPI(mContext, EConstants.WEIXIN_APP_ID);//测试账号wx7e97dc6531f3cf94//wx415f8635e280b198
            this.mShareIWXAPI.registerApp(EConstants.WEIXIN_APP_ID);
            System.out.println("Share WEIXIN_APP_ID==>>::: " +EConstants.WEIXIN_APP_ID);
            if (isWxAppInstalled()) {

            } else {
                Toast.makeText(mContext, "尚未安装微信,请安装微信后再试", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (Exception e) {
            e.getStackTrace();
        }


    }

    public IWXAPI getmShareIWXAPI() {
        return this.mShareIWXAPI;
    }

    //是否安装微信
    public boolean isWxAppInstalled() {
        return this.mShareIWXAPI != null && this.mShareIWXAPI.isWXAppInstalled();
    }

    /**
     * 微信4.2以上支持，如果需要检查微信版本支持API的情况， 可调用IWXAPI的getWXAppSupportAPI方法,0x21020001及以上支持发送朋友圈
     *
     * @return
     */
    public boolean isSupportWx() {
        return this.mShareIWXAPI != null && this.mShareIWXAPI.isWXAppInstalled() && this.mShareIWXAPI.isWXAppSupportAPI();
    }

    private void sendReq(SendMessageToWX.Req req) {
        this.mShareIWXAPI.sendReq(req);
        System.out.println("Share==>>::: " + "WxShareHelper sendReq：" + req.message + "\n" + req.openId + "\n"
                + req.transaction + "\n" + req.getType());
    }


    public void sendReq(ShareMsgObj shareMsgObj) {
        if (shareMsgObj == null) {
            return;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        if (shareMsgObj.getWxType() == 1) {
            req.scene = SendMessageToWX.Req.WXSceneSession;//会话
        } else if (shareMsgObj.getWxType() == 2) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;//朋友圈
        }
        switch (shareMsgObj.getShareType()) {
            case ShareMsgObj.ShareType.SHARE_TEXT:
                WXTextObject textObject = new WXTextObject();
                textObject.text = shareMsgObj.getText();
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = textObject;
                msg.description = shareMsgObj.getMsgDesription();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                this.sendReq(req);

                break;
            case ShareMsgObj.ShareType.SHARE_IMAGE:
                Bitmap bmp = shareMsgObj.getBmp();
                WXImageObject imageObject = new WXImageObject(bmp);
                WXMediaMessage msg1 = new WXMediaMessage();
                msg1.mediaObject = imageObject;
                //Bitmap thumbBmp=Bitmap.createScaledBitmap(bmp,0,0,true);
                msg1.setThumbImage(shareMsgObj.getThunbBmp());
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg1;
                this.sendReq(req);

                break;
            case ShareMsgObj.ShareType.SHARE_MP3:
                WXMusicObject musicObject = new WXMusicObject();
                musicObject.musicUrl = shareMsgObj.getUrl();
                WXMediaMessage msg2 = new WXMediaMessage();
                msg2.mediaObject = musicObject;
                msg2.description = shareMsgObj.getMsgDesription();
                msg2.title = shareMsgObj.getMsgTitle();
                msg2.setThumbImage(shareMsgObj.getThunbBmp());
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg2;
                this.sendReq(req);
                break;
            case ShareMsgObj.ShareType.SHARE_VIEDO:
                WXVideoObject videoObject = new WXVideoObject();
                videoObject.videoUrl = shareMsgObj.getUrl();
                WXMediaMessage msg3 = new WXMediaMessage(videoObject);
                msg3.title = shareMsgObj.getMsgTitle();
                msg3.description = shareMsgObj.getMsgDesription();
                msg3.setThumbImage(shareMsgObj.getThunbBmp());
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg3;
                this.sendReq(req);
                break;
            case ShareMsgObj.ShareType.SHARE_WEB:
                WXWebpageObject wxWebpageObject = new WXWebpageObject();
                wxWebpageObject.webpageUrl = shareMsgObj.getUrl();
                WXMediaMessage msg4 = new WXMediaMessage(wxWebpageObject);
                msg4.title = shareMsgObj.getMsgTitle();
                msg4.description = shareMsgObj.getMsgDesription();
                msg4.setThumbImage(shareMsgObj.getThunbBmp());
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg4;
                this.sendReq(req);
                break;
            default:
                break;
        }
        System.out.println("Share==>> " + "WxShareHelper sendReq：" + req.openId + "\n"
                + req.transaction + "\n" + req.getType());

    }

    public void dealWithWeiXin0nResp(BaseReq baseReq) {
        if (baseReq != null) {

        }

    }

    public void dealWithWeixinOnResp(BaseResp baseResp) {
        this.isNeedDealWithResult = true;
        this.mbaseResp = baseResp;
        System.out.println("Share==>> " + "WxShareHelper dealWithWeixinOnResp：" + mbaseResp.errStr + mbaseResp.errCode);
    }

    public void onResumeResultData() {
        if (isNeedDealWithResult) {
            isNeedDealWithResult = false;
            Toast toast;
            switch (mbaseResp.errCode) {
                case BaseResp.ErrCode.ERR_OK://发送成功
                    if (mWxShareListener != null)
                        mWxShareListener.onWxShareSucc("分享成功" + mbaseResp.errCode);
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL://发送取消
                    boolean flag=false;
                    if (mWxShareListener != null) {
                       flag= mWxShareListener.onWxShareCancel();
                    }
                    if (!flag)//当取消被实现并返回true时此处不再弹提示
                        ToastUtil.INSTANCE.toastCenter(mContext, "分享取消", R.mipmap.ic_cancel);
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED://发送被拒绝
                    toast = Toast.makeText(mContext, "分享被拒绝", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    if (mWxShareListener != null)
                        mWxShareListener.onWxShareFailure(mbaseResp.errCode, "分享失败" + mbaseResp.errCode);
                    break;
                case BaseResp.ErrCode.ERR_UNSUPPORT://不支持错误
                    toast = Toast.makeText(mContext, "不支持错误", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    if (mWxShareListener != null)
                        mWxShareListener.onWxShareFailure(mbaseResp.errCode, "分享失败" + mbaseResp.errCode);
                    break;
                default://发送返回 未知错误
                    toast = Toast.makeText(mContext, "未知错误", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    if (mWxShareListener != null)
                        mWxShareListener.onWxShareFailure(mbaseResp.errCode, "分享失败" + mbaseResp.errCode);
                    break;
            }
        }
    }


    public void release() {
        if (this.mShareIWXAPI != null) {
            this.mShareIWXAPI.unregisterApp();
            this.mShareIWXAPI = null;
        }
        this.mbaseResp = null;
        this.mWxShareListener = null;
        instance = null;
    }


}
